﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Geotools.Geometries;
using System.Collections.Generic;
using AzukiMap.Tools;
using AzukiMap.MapSource.Vector;

namespace AzukiMap.MapSource
{
    public class LocalVectorSource : VectorSource
    {
        List<LocalVectorData> _items;
        GeometryUtil _geomUtil;

        public List<LocalVectorData> Source
        {
            get { return _items; }
            set { _items = value; }
        }

        public LocalVectorSource(string name, VectorSourceTypes vectorType, int srid, CoordinationUnits coordUnit)
            : base(name,vectorType,srid,coordUnit)
        {
            _items = new List<LocalVectorData>();
            _geomUtil = new GeometryUtil();
        }

        public void Add(LocalVectorData item)
        {
            _items.Add(item);
        }

        public void Remove(LocalVectorData item)
        {
            _items.Remove(item);
        }

        public void Clear()
        {
            _items.Clear();
        }

        public void SetMaxExtent()
        {
            double minXAll = double.PositiveInfinity;
            double maxXAll = double.NegativeInfinity;
            double minYAll = double.PositiveInfinity;
            double maxYAll = double.NegativeInfinity;
            foreach (LocalVectorData item in _items)
            {
                IGeometry geom = item.Geometry;
                GTEnvelope env= geom.GetEnvelopeInternal();
                double minX = env.MinX;
                double minY = env.MinY;
                double maxX = env.MaxX;
                double maxY = env.MaxY;
                minXAll = (minX < minXAll) ? minX : minXAll;
                minYAll = (minY < minYAll) ? minY : minYAll;
                maxXAll = (maxX > maxXAll) ? maxX : maxXAll;
                maxYAll = (maxY > maxYAll) ? maxY : maxYAll;
            }
            if (minXAll != double.PositiveInfinity)
            {
                GTEnvelope extent = new GTEnvelope(minXAll, maxXAll, minYAll, maxYAll);
                _maxExtent = extent;
            }
        }

        public IEnumerable<LocalVectorData> GetItemsInExtent(GTPolygon extent)
        {
            foreach (LocalVectorData item in _items)
            {
                //if ( extent.Overlaps(item.Geometry.GetEnvelope()))
                if ( extent.Intersects(item.Geometry.GetEnvelope()))
                {
                    yield return item;
                }
            }
        }
    }

    public class LocalVectorData
    {
        public int Id;
        public GTGeometry Geometry;
        public int ExpressionId = -1;
        public object Attribute;
    }
}
